<?php
/**
 * @Author: xuzhiyi
 * @Date:   2016-02-16 20:57:17
 * @Last Modified by:   xuzhiyi
 * @Last Modified time: 2016-03-03 09:31:28
 * ------------------------------------------------ *
 * 店铺管理                                        *
 * ------------------------------------------------ */
namespace Admin\Model;
//use Think\Model\RelationModel;

class ShopsModel extends CommonModel{

//获取列表

	public function getShops(){
	$a=M('shops');
	//$result = $a->where('shopFlag!=-1')->select();
	$result =$a->join('as a left join '.C("DB_PREFIX").'goods_cats as b on a.goodsCatId1=b.catId')->join('left join '.C("DB_PREFIX").'users as c on a.userId=c.userId')->field('a.*,b.catName,c.userName')->where('a.shopFlag=1')->select();
	if(false!==$result){
		return $result;
	}
	return false;

}

// 待审核列表

     public function getShopsPendding(){
        $a = M('shops');
        $result =$a->join('as a left join '.C("DB_PREFIX").'goods_cats as b on a.goodsCatId1=b.catId')->join('left join '.C("DB_PREFIX").'users as c on a.userId=c.userId')->field('a.*,b.catName,c.userName')->where('shopStatus<=0 and shopFlag=1')->select();
		if(false!==$result){
			return $result;
		}
		return false;
	 }


//登录关键字/用户名或手机号或邮箱登录

	 public function checkLoginKey($val,$id = 0){
	 	$sql = " (loginName ='%s' or userPhone ='%s' or userEmail='%s') and userFlag=1";
	 	$keyArr = array($val,$val,$val);
	 	if($id>0)$sql.=" and userId!=".(int)$id;
	 	$m = M('users');
	 	$rs = $m->where($sql,$keyArr)->count();
	    if($rs==0)return true;
	    return false;
	 }

// 新增

	 public function addShops(){
	 		 	
	 	//先建立账号
	 	$hasLoginName = $this->checkLoginKey(I("loginName"));

	 	$hasUserPhone = $this->checkLoginKey(I("userPhone"));
	 	if($hasLoginName==false || $hasUserPhone==false){
	 		
	 		return false;
	 	}
	 	//用户资料
	 	$data = array();
	 	$data["loginName"] = I("loginName");
		$data["loginSecret"] = rand(1000,9999);
		$data["loginPwd"] = md5(I('loginPwd').$data['loginSecret']);
		$data["userName"] = I("userName");
		$data["userPhone"] = I("userPhone");


		//店铺资料
		$sdata = array();
		$sdata["shopSn"] = I("shopSn");
		$sdata["areaId1"] = (int)I("areaId1");
		$sdata["areaId2"] = (int)I("areaId2");
		$sdata["areaId3"] = (int)I("areaId3");
		$sdata["goodsCatId1"] = (int)I("goodsCatId1");
		$sdata["shopName"] = I("shopName");
		
		
		$sdata["shopAddress"] = I("shopAddress");
		$sdata["bankId"] = (int)I("bankId");
		$sdata["bankNo"] = I("bankNo");
		
		$sdata["shopTel"] = I("shopTel");
		if($this->checkEmpty($data) && $this->checkEmpty($sdata)){
			//return "888888888888888888888888";

			//$sdata["shopImg"] = I("shopImg");
			$data["userStatus"] = (int)I("userStatus",1);
			$data["userType"] = (int)I("userType",1);
			$data["userEmail"] = I("userEmail");
			$data["userQQ"] = I("userQQ");
			$data["userScore"] = I("userScore",0);
		    $data["userTotalScore"] = I("userTotalScore",0);
		    $data["userFlag"] = 1;
		    $data["createTime"] = date('Y-m-d H:i:s');
			$m = M('users');
			//插入用户数据
			$userId = $m->add($data);
			if(false !== $userId){
				if(!empty($_FILES['shopImg']['tmp_name'])){
					$shopImg=$this->upAvatar('shopImg');
					if($shopImg==false){
						return false;
					}
					$sdata["shopImg"] = $shopImg;
				}else{
					$sdata["shopImg"] = $GLOBALS['COMMON']['shopLogo'];
				}

				$sdata["userId"] = $userId;
				$sdata["isSelf"] = (int)I("isSelf",0);
				if($sdata["isSelf"]==1){
					$sdata["deliveryType"] = 1;
				}else{
					$sdata["deliveryType"] = 0;
				}
				$sdata["serviceStartTime"] = I("serviceStartTime");//
				$sdata["serviceEndTime"] = I("serviceEndTime");//
				$sdata["shopCompany"] = I("shopCompany");// 
				$sdata["deliveryStartMoney"] = I("deliveryStartMoney",0);
		        $sdata["deliveryCostTime"] = I("deliveryCostTime",0);
				$sdata["deliveryFreeMoney"] = I("deliveryFreeMoney",0);
		        $sdata["deliveryMoney"] = I("deliveryMoney",0);
				$sdata["avgeCostMoney"] = I("avgeCostMoney",0);
				$sdata["longitude"] = (float)I("longitude");
				$sdata["latitude"] = (float)I("latitude");
				$sdata["mapLevel"] = (int)I("mapLevel",13);
				$sdata["isInvoice"] = (int)I("isInvoice",1);
				$sdata["shopStatus"] = (int)I("shopStatus",1);
				$sdata["shopAtive"] = (int)I("shopAtive",1);
				$sdata["shopFlag"] = 1;
				$sdata["createTime"] = date('Y-m-d H:i:s');
			    $sdata['statusRemarks'] = I('statusRemarks');
			    $sdata['qqNo'] = I('qqNo');
			    $sdata["invoiceRemarks"] = I("invoiceRemarks");
				$m = M('shops');
				//插入店铺数据
				$shopId = $m->add($sdata);
				if(false !== $shopId){					
				    $data = array();
				    $data['shopId'] = $shopId;
				    $m = M('shop_scores');
				    //增加商家评分记录
				    $m->add($data);
					return true;
				    
				}
				if(!empty($shopImg)){
					$this->delAvatar($shopImg);
				}
			}
			
		}
		
		return false;
	 } 

 
// 修改

	 public function editShops(){
	 	
	 	$shopId = (int)I('shopId',0);
	 	
	 	$m = M('shops');
	 	//获取店铺资料
	 	$shops = $m->where("shopId=".$shopId)->find();
	 	$oldShopId=$shops['shopImg'];
	    //检测手机号码是否存在
	 	if(I("userPhone")!=''){
	 		$hasUserPhone = $this->checkLoginKey(I("userPhone"),$shops['userId']);
	 		if($hasUserPhone==false){
	 			
	 		    return false;
	 		}
	 	}
	    $data = array();
		$data["shopSn"] = I("shopSn");
		$data["areaId1"] = (int)I("areaId1");
		$data["areaId2"] = (int)I("areaId2");
		$data["areaId3"] = (int)I("areaId3");
		$data["goodsCatId1"] = (int)I("goodsCatId1");
		$data["isSelf"] = (int)I("isSelf",0);
		if($data["isSelf"]==1){
			$data["deliveryType"] = 1;
		}else{
			$data["deliveryType"] = 0;
		}
		$data["shopName"] = I("shopName");
		$data["shopCompany"] = I("shopCompany");
		$data["shopAddress"] = I("shopAddress");
		$data["deliveryStartMoney"] = I("deliveryStartMoney",0);
		$data["deliveryCostTime"] = I("deliveryCostTime",0);
		$data["deliveryFreeMoney"] = I("deliveryFreeMoney",0);
		$data["deliveryMoney"] = I("deliveryMoney",0);
		$data["avgeCostMoney"] = I("avgeCostMoney",0);
		$data["bankId"] = I("bankId");
		$data["bankNo"] = I("bankNo");
		$data["longitude"] = (float)I("longitude");
		$data["latitude"] = (float)I("latitude");
		$data["mapLevel"] = (int)I("mapLevel",13);
		$data["isInvoice"] = I("isInvoice",1);
		$data["serviceStartTime"] = I("serviceStartTime");
		$data["serviceEndTime"] = I("serviceEndTime");
		$data["shopStatus"] = (int)I("shopStatus",0);
		$data["shopAtive"] = (int)I("shopAtive",1);
		$data["shopTel"] = I("shopTel");
		if($this->checkEmpty($data)){
			if(!empty($_FILES['shopImg']['tmp_name'])){
				$shopImg=$this->upAvatar('shopImg');
				if($shopImg==false){
					return false;
				}
				$data["shopImg"] = $shopImg;
			}
			$data['qqNo'] = I('qqNo');
			$data["invoiceRemarks"] = I("invoiceRemarks");
			$rs = $m->where("shopId=".$shopId)->save($data);
		    if(false !== $rs){
		    	//就图片非默认就删除
		    	if(!empty($shopImg) && $oldShopImg!=$GLOBALS['COMMON']['shopLogo']){
		    		$this->delAvatar($oldShopImg);
		    	}

		    	$shopMessage = '';
		    	//如果[已通过的店铺]被改为未审核的话也要停止了该店铺的商品
		    	if($shops['shopStatus']!=$data['shopStatus']){
					if($data['shopStatus']!=1){
						$gdata=array();
						$gdata['isSale']=0;
						$gdata['goodsStatus']=0;
						M('goods')->where("shopId=".$shopId)->save($gdata);
			 	        $shopMessage = "您的店铺状态已被改为“未审核”状态，如有疑问请与商场管理员联系。";
					}
					if($shops['shopStatus']!=1 && $data['shopStatus']==1){
						$shopMessage = "您的店铺状态已被改为“已审核”状态，您可以出售自己的商品啦。。";
					}
					$mdata = array(
						'msgType' => 0,
						'sendUserId' => session('admin.managerId'),
						'receiveUserId' => $shops['userId'],
						'msgContent' => $shopMessage,
						'createTime' => date('Y-m-d H:i:s'),
						'msgStatus' => 0,
						'msgFlag' => 1,
					);
					M('messages')->add($mdata);
		    	}
		    	//检查用户类型
		    	$m = M('users');
		    	$userType = $m->where('userId='.$shops['userId'])->getField('userType');
		    	
		    	//保存用户资料		    	
		    	$data = array();
		    	$data["userName"] = I("userName");
		        $data["userPhone"] = I("userPhone");
		       
		        //如果是普通用户则提升为店铺会员
		        if($userType==0){
		        	$data["userType"] = 1;
		        }
		        $urs = $m->where("userId=".$shops['userId'])->save($data);
				return true;
			}
			if(!empty($shopImg)){
				$this->delAvatar($shopImg);
			}
		}
	
		return false;
	 } 

//通过店铺
	 public function startShops(){
	 	$shopId = I('shopId',0);
	 	
	 	$m = M('shops');
	 	//获取店铺资料
	 	$shops = $m->where("shopId=".$shopId)->find();
	 	$data = array();
	 	$data['shopStatus'] = (int)I('shopStatus',1);
	 	
	 	if($this->checkEmpty($data)){
	 		$data['statusRemarks'] = I('statusRemarks');
		 	$rs = $m->where("shopId=".$shopId)->save($data);
			if(false !== $rs){
				$shopMessage = '';
				//如果[已通过的店铺]被改为未审核的话也要停止了该店铺的商品
				if($shops['shopStatus']!=$data['shopStatus']){
					if($data['shopStatus']!=1){
						$gdata=array();
						$gdata['isSale']=0;
						$gdata['goodsStatus']=0;
						M('goods')->where("shopId=".$shopId)->save($gdata);
			 	        $shopMessage = "您的店铺状态已被改为“未审核”状态，如有疑问请与商场管理员联系。";
					}
					if($shops['shopStatus']!=1 && $data['shopStatus']==1){
						$shopMessage = "您的店铺状态已被改为“已审核”状态，您可以出售自己的商品啦。。";
					}
					$mdata = array(
						'msgType' => 0,
						'sendUserId' => session('admin.managerId'),
						'receiveUserId' => $shops['userId'],
						'msgContent' => $shopMessage,
						'createTime' => date('Y-m-d H:i:s'),
						'msgStatus' => 0,
						'msgFlag' => 1,
					);
					M('messages')->add($mdata);
				}
				return true;
			}
		}
		return false;
	 }

// 停止或者拒绝店铺

	 public function stopShops(){
	 	$shopId = I('shopId',0);
	 	
	 	$m = M('shops');
	 	//获取店铺资料
	 	$shops = $m->where("shopId=".$shopId)->find();
	 	$data = array();
	 	$data['shopStatus'] = (int)I('shopStatus',-1);
	 	$data['statusRemarks'] = I('statusRemarks');
	 	if($this->checkEmpty($data)){
		 	$rs = $m->where("shopId=".$shopId)->save($data);
			if(false !== $rs){
				//如果[已通过的店铺]被改为停止或者拒绝的话也要停止了该店铺的商品
				if($shops['shopStatus']!=$data['shopStatus']){
					$shopMessage = '';
					if($data['shopStatus']!=1){
						$gdata=array();
						$gdata['isSale']=0;
						$gdata['goodsStatus']=0;
						M('goods')->where("shopId=".$shopId)->save($gdata);
			 	        if($data['shopStatus']==0){
			 	        	$shopMessage = "您的店铺状态已被改为“未审核”状态，如有疑问请与商场管理员联系。";
			 	        }else{
			 	        	$shopMessage = I('statusRemarks');
			 	        }
					}
					$mdata = array(
						'msgType' => 0,
						'sendUserId' => session('admin.managerId'),
						'receiveUserId' => $shops['userId'],
						'msgContent' => $shopMessage,
						'createTime' => date('Y-m-d H:i:s'),
						'msgStatus' => 0,
						'msgFlag' => 1,
					);
					M('messages')->add($mdata);
				}
				return true;
			}
			
	 	}
		return false;
	 }
	 



// 删除
	 public function delShops(){
	 	$shopId = (int)I('shopId');
	    $m = M('shops');
	    //下架所有商品
	    $gdata=array();
		$gdata['isSale']=0;
		$gdata['goodsStatus']=0;
		M('goods')->where("shopId=".$shopId)->save($gdata);
		$uesrId=$m->where("shopId=".$shopId)->getField('userId');
		//删除登录账号
		$udata=array();
		$udata['userFlag']=-1;
		M('users')->where("userId=".$userId)->save($gdata);
		//标记店铺删除状态
	    $data = array();
		$data["shopFlag"] = -1;
		$data["shopStatus"] = -2;
	 	$rs = $m->where("shopId=".$shopId)->save($data);
	    if(false !== $rs){
			return true;
		}
		return false;
	 }
 
// 获取待审核的店铺数量
	 public function getPenddingShopsNum(){
	 	$m = M('shops');
	 	$num=$m->where('shopStatus=0 and shopFlag=1')->count();
	 	return $num;
	 }
}